package com.miyake.dsp.osa.lab;

import java.util.LinkedList;
import java.util.List;

import com.miyake.dsp.ComplexArray;
import com.miyake.dsp.ScilabExecute;

public class Fitting2 {

	private String formula;
	private double[] originalX;
	private double[] originalY;
	
	public Fitting2(String formula) {
		this.formula = formula;
	}
	
	public void setOriginalData(double[] x, double[] y) {
		this.originalX = x;
		this.originalY = y;
	}
	
	public double[] getInterpolated(double[] interpolatedX) {
		List<String> cmd = new LinkedList<String>();
	//	cmd.add("x0=[-2250000;3000;-0.1;1500;10;0;0;0;0];");
		//cmd.add("x0=[1;1;1;1;1;1;1;0;0];");
		cmd.add("x0=[0;0;0;0;0;0;0;0;0];");
		cmd.add("deff('y=yth(t,x)','" + this.formula + "');");
		cmd.add("deff('e=myfun(x,d1,d2)', 'e=(yth(d1, x) - d2)');");
		cmd.add("[f,xopt,gropt]=leastsq(list(myfun,data1',data2'),x0);");
		cmd.add("ret=yth(data3,xopt)");
		
		List<ComplexArray> data = new LinkedList<ComplexArray>();
		data.add(new ComplexArray(originalX));
		data.add(new ComplexArray(originalY));
		data.add(new ComplexArray(interpolatedX));
		return ScilabExecute.execute(cmd, data, "ret").getRealPart();
	}

	public double getAt(double center) {
		double[] x = new double[1];
		x[0] = center;
		return getInterpolated(x)[0];
	}
}


